//
//  AssertTableViewController.m
//  objective_c_language
//
//  Created by 王玉龙 on 2018/6/9.
//  Copyright © 2018年 longlong. All rights reserved.
//

NSString * const NSCustomException = @"这是一个自定义的异常";

#import "AssertTableViewController.h"
#import <objc/runtime.h>
#import <objc/message.h>
#import <CoreNFC/CoreNFC.h>

@interface AssertTableViewController ()
@property (nonatomic ,strong) NSArray<NSString *> *itemArray;
@end

@implementation AssertTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    cell.textLabel.text = self.itemArray[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        [self assertMethod:indexPath.row];
    }
    else if (indexPath.row == 1)
    {
        [self readFile:nil];
    }
    else if (indexPath.row == 2)
    {
        [self handleException];
    }
    else if (indexPath.row == 3)
    {
        [self handleExceptionArray];
    }
    else if (indexPath.row == 4)
    {
        [self creatNSException];
    }
}

- (void)assertMethod:(NSInteger)value
{
    if (value > 0)
    {
        
    }
    else
    {
        //值必须非正数
        value = 3;
        NSAssert((value <= 0), @"value 是无效的，它必须是非正数");
        NSCAssert((value <= 0), @"value 是无效的，它必须是非正数");
    }
}

- (void)readFile:(NSString *)filePath
{
    //文件路径不能为空
    NSParameterAssert(filePath != nil);
}

- (void)handleException
{
    @try
    {
        //可能抛出异常的代码
        [self readFile:nil];
    }
    @catch(NSException *exception)
    {
        //处理异常的代码
        
        NSLog(@"exception == %@",exception);
    }
    @finally
    {
        //释放资源的代码
    }
}

- (void)handleExceptionArray
{
    NSArray *array = @[@"1"];

    @try
    {
        NSLog(@"array[2] --- %@",array[2]);
    }
    @catch(NSException *exception)
    {
        NSLog(@"callStackSymbols == \n %@",exception.callStackSymbols);
        NSLog(@"callStackReturnAddresses == \n %@",exception.callStackReturnAddresses);

        NSLog(@"exception == \n %@",[self dictionaryRepresentationWithError:exception]);
//        @throw [NSNull null];
    }
    @finally
    {
    }
}

- (void)creatNSException
{
    NSException *exception = [NSException exceptionWithName:NSCustomException reason:@"why exception" userInfo:@{@"ExceptionSuggest":@"Kill App"}];
    NSLog(@"exception --- \n %@",[self dictionaryRepresentationWithError:exception]);
    NSLog(@"callStackSymbols --- \n %@",exception.callStackSymbols);
    [exception raise];//激发异常

    
    
    @try
    {
        NSLog(@"callStackReturnAddresses --- \n %@",exception.callStackReturnAddresses);
    }
    @catch(NSException *exception)
    {
        NSLog(@"callStackSymbols == \n %@",exception.callStackSymbols);
        NSLog(@"callStackReturnAddresses == \n %@",exception.callStackReturnAddresses);
        
        NSLog(@"exception == \n %@",[self dictionaryRepresentationWithError:exception]);
        //        @throw [NSNull null];
    }
    @finally
    {
    }

}

- (NSArray<NSString *> *)itemArray
{
    if (_itemArray == nil)
    {
        _itemArray = @[@"内部不变",@"内部不变",@"异常断言",@"异常数组越界",@"实例化NSException"];
    }
    return _itemArray;
}

- (NSDictionary *)dictionaryRepresentationWithError:(NSException *)exception
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    unsigned int count = 0;
    Ivar *iavrList = class_copyIvarList(NSException.class, &count);
    for (int i = 0; i < count; i ++)
    {
        Ivar ivar = iavrList[i];
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        if ([exception respondsToSelector:@selector(valueForKey:)] && ![key containsString:@"reserved"])
        {
            if ([exception valueForKey:key])
            {
                [mutableDict setValue:[exception valueForKey:key] forKey:key];
            }
            else
            {
                [mutableDict setValue:[NSNull null] forKey:key];
            }
        }
    }
    free(iavrList);
    return [NSDictionary dictionaryWithDictionary:mutableDict];
}
@end
